/**
 * 加载并解析env环境变量
 */
const fs = require('fs')
const path = require('path')
const parse = require('dotenv').parse
const expand = require('dotenv-expand').expand

const resolveFileList = (mode) => {
  return [`.env`, `.env.local`, `.env.${mode}`, `.env.${mode}.local`]
}

/**
 * 判断文件是否存在
 * @param {String} file
 * @returns
 */
function tryStatSync(file) {
  try {
    return fs.statSync(file, { throwIfNoEntry: false })
  } catch (error) {}
}

/**
 * 根据前缀，过滤出符合要求的环境变量
 * @param {Object<string, any>} parsed
 */
function filterPrefix(parsed) {
  const prefix = 'VUE_APP_'

  const env = {}

  for (let [key, value] of Object.entries(parsed)) {
    if (key.startsWith(prefix)) {
      env[key] = value
    }
  }

  return env
}

function loadEnv() {
  const mode = process.env.NODE_ENV || 'development'

  const envList = resolveFileList(mode)

  // flatMap 可以过滤空的 []
  let result = envList.flatMap((p) => {
    const filePath = path.resolve(process.cwd(), p)

    if (!tryStatSync(filePath)?.isFile()) return []

    let content = fs.readFileSync(p)

    let t1 = parse(content)

    return Object.entries(t1)
  })

  // 将结果解析成对象形式
  let parsed = Object.fromEntries(result)

  expand({ parsed })

  return filterPrefix(parsed)
}

exports.loadEnv = loadEnv

exports.tryStatSync = tryStatSync
